package com.xindaoapp.happypet.ui;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.xindaoapp.happypet.R;
import com.xindaoapp.happypet.activity.HomeBannerDetailActivity;
import com.xindaoapp.happypet.bean.HomeBanner;
import com.xindaoapp.happypet.bean.HomeBannerEntity;
import com.xindaoapp.happypet.bean.MainZuixinData;
import com.xindaoapp.happypet.bean.MainZuixinData.MainTiezi;
import com.xindaoapp.happypet.utils.CommonParameter;
import com.xindaoapp.happypet.utils.CommonUtil;
import com.xindaoapp.happypet.utils.Constants;
import com.xindaoapp.happypet.utils.IRequest;
import com.xindaoapp.happypet.view.RollViewPager;

/**
 * 首页_美图
 * 
 * @author Stone
 * 
 */
public class MeituFragment extends BaseFragment {

    public static Fragment newInstance() {
        Fragment fragment = new MeituFragment();
        Bundle bundle = new Bundle();
        fragment.setArguments(bundle);
        return fragment;
    }

    private PullToRefreshListView mPullToRefreshListView;
    private MyAdapter mAdapter;
    private final List<MainTiezi> mList = new ArrayList<MainZuixinData.MainTiezi>();

    private final boolean mFrist = true;
    private boolean isLoading;
    /** 轮播图 */
    private View mHeadView;
    private View mFootView;
    private LinearLayout mViewPagerContainer;
    private TextView mTvDescription;
    private LinearLayout mPointsContainer;
    private List<HomeBanner> mBanners;
    private ArrayList<View> mDotLists;
    private RollViewPager mRollViewPager;
    private int currentPage = 1;
    private View mBackToTop;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return mView = inflater.inflate(R.layout.zuixinfragment, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }

    @Override
    protected void initViews() {
        super.initViews();
        mBackToTop = mView.findViewById(R.id.iv_back_top);
        mPullToRefreshListView = (PullToRefreshListView) mView.findViewById(R.id.listview);
        mPullToRefreshListView.setMode(Mode.PULL_FROM_START);

        mHeadView = LayoutInflater.from(mContext).inflate(R.layout.head_zuixinfragment, null);
        mViewPagerContainer = (LinearLayout) mHeadView.findViewById(R.id.viewpager1);
        mViewPagerContainer.setLayoutParams(new RelativeLayout.LayoutParams(
                LayoutParams.MATCH_PARENT, CommonParameter.sScreenWidth * 248 / 640));
        mTvDescription = (TextView) mHeadView.findViewById(R.id.tv_image_description1);
        mPointsContainer = (LinearLayout) mHeadView.findViewById(R.id.ll_points1);

        mFootView = LayoutInflater.from(mContext).inflate(R.layout.item_loading, null);
        mPullToRefreshListView.getRefreshableView().addFooterView(mFootView);
        mAdapter = new MyAdapter();
        mPullToRefreshListView.getRefreshableView().setAdapter(mAdapter);

        mPullToRefreshListView.setOnRefreshListener(new OnRefreshListener<ListView>() {

            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                mList.clear();
                currentPage = 1;
                loadDatas();
            }
        });

        mPullToRefreshListView.setOnScrollListener(new OnScrollListener() {
            private boolean isBottom;


            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                // TODO Auto-generated method stub
                if (scrollState == OnScrollListener.SCROLL_STATE_IDLE && isBottom) {
                    isLoading = true;
                    loadMore();
                }
            }


            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
                    int totalItemCount) {
                // TODO Auto-generated method stub
                int w = mAdapter.getCount();
                if (w == firstVisibleItem + visibleItemCount - 2) {
                    isBottom = true;
                }

                if (firstVisibleItem >= 10) {
                    mBackToTop.setVisibility(View.VISIBLE);
                } else {
                    mBackToTop.setVisibility(View.GONE);
                }

            }
        });


        mBackToTop.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                mPullToRefreshListView.getRefreshableView().setSelection(0);
            }
        });



    }

    private void loadMore() {
        // TODO Auto-generated method stub
        currentPage++;
        getMoccaApi().getBeautifulList(currentPage, Constants.PAGE_SIZE,
                new IRequest<MainZuixinData>() {

                    @Override
                    public void request(MainZuixinData t) {
                        isLoading = false;
                        if (null != t) {
                            if (t.array.size() == 0) {
                                // currentPage--;
                                Toast.makeText(mContext, "没有更多数据 !", Toast.LENGTH_SHORT).show();
                                mFootView.setVisibility(View.GONE);
                            } else {
                                mList.addAll(t.array);
                                mAdapter.notifyDataSetChanged();
                                mFootView.setVisibility(View.VISIBLE);
                            }
                        } else {
                            Toast.makeText(mContext, "网络错误，请检查网络！", Toast.LENGTH_SHORT).show();
                        }

                    }
                });

    }

    @Override
    protected void initEvents() {
        super.initEvents();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    protected void loadDatas() {
        super.loadDatas();

        getBannerData();
        getData();

    }



    private void getBannerData() {

        // getMoccaApi().getIndexBanner("group", new IRequest<HomeBannerEntity>() {
        getMoccaApi().getIndexBanner("index", new IRequest<HomeBannerEntity>() {
            @Override
            public void request(HomeBannerEntity t) {

                if (null != t) {
                    onDataArrived(true);
                    if (t.getArray().size() == 0) {
                        // onDataArrivedEmpty();
                    } else {
                        mBanners = t.getArray();
                        prepareViewPage(mContext, mBanners);
                    }
                } else {
                    onDataArrived(false);
                }
                // mPullToRefreshListView.onRefreshComplete();

            }
        });
    }

    public void prepareViewPage(final Context context, final List<HomeBanner> list) {
        List<String> titleList = new ArrayList<String>();
        List<String> imageUrlList = new ArrayList<String>();
        for (HomeBanner homeBanner : list) {
            titleList.add(homeBanner.getTitle());
            imageUrlList.add(homeBanner.getCoverpath());
        }
        initDots(list.size());
        mRollViewPager =
                new RollViewPager(context, mDotLists, R.drawable.point_normal,
                        R.drawable.point_enable, new RollViewPager.MyOnTouchCllickCallBack() {
                            @Override
                            public void OnTouchCllick(int position) {
                                String type = list.get(position % list.size()).getType();
                                if (type.equals("web")) {// 跳转到详情
                                    Intent intent1 =
                                            new Intent(context, HomeBannerDetailActivity.class);
                                    intent1.putExtra("url", list.get(position % list.size())
                                            .getLink());
                                    context.startActivity(intent1);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                } else if (type.equals("appthread")) {// 跳转到帖子详情
                                    Intent intent2 = new Intent(context, PostDetailActivity.class);
                                    intent2.putExtra(Constants.KEY_POST_TID,
                                            list.get(position % list.size()).getLink());
                                    context.startActivity(intent2);
                                    getActivity().overridePendingTransition(
                                            R.anim.new_dync_in_from_right,
                                            R.anim.new_dync_out_to_left);
                                }
                            }
                        });
        mRollViewPager.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                CommonParameter.sScreenWidth * 248 / 640));
        mRollViewPager.setTitle(mTvDescription, titleList);
        mRollViewPager.setImageUrl(imageUrlList);
        mRollViewPager.startRoll();
        mViewPagerContainer.removeAllViews();
        mViewPagerContainer.addView(mRollViewPager);

        if (list.size() > 0
                && mPullToRefreshListView.getRefreshableView().getHeaderViewsCount() <= 1) {
            mPullToRefreshListView.getRefreshableView().addHeaderView(mHeadView);
            mPullToRefreshListView.getRefreshableView().setAdapter(mAdapter);
        }

    }

    private void initDots(int size) {
        mDotLists = new ArrayList<View>();
        mPointsContainer.removeAllViews();
        for (int i = 0; i < size; i++) {
            LinearLayout.LayoutParams layoutParams =
                    new LinearLayout.LayoutParams(CommonUtil.dip2px(mContext, 5),
                            CommonUtil.dip2px(mContext, 5));
            layoutParams.setMargins(5, 0, 5, 8);
            ImageView m = new ImageView(mContext);
            if (i == 0) {
                m.setBackgroundResource(R.drawable.point_enable);
            } else {
                m.setBackgroundResource(R.drawable.point_normal);
            }
            m.setLayoutParams(layoutParams);
            mDotLists.add(m);
            mPointsContainer.addView(m);
        }
    }

    private void getData() {
        getMoccaApi().getBeautifulList(Constants.PAGE_FIRST, Constants.PAGE_SIZE,
                new IRequest<MainZuixinData>() {

                    @Override
                    public void request(MainZuixinData t) {
                        if (null != t) {
                            onDataArrived(true);
                            if (t.array.size() == 0) {
                                onDataArrivedEmpty();
                            } else {
                                mList.addAll(t.array);

                                mPullToRefreshListView.setAdapter(mAdapter);
                                mFootView.setVisibility(View.VISIBLE);
                            }
                        } else {
                            onDataArrived(false);
                        }
                        mPullToRefreshListView.onRefreshComplete();

                    }
                });

    }

    class MyAdapter extends BaseAdapter {


        int num = 0;

        @Override
        public int getCount() {

            if (mList.size() % 2 == 0) {
                return num = mList.size() / 2;
            } else {
                return num = mList.size() / 2 + 1;
            }
        }

        @Override
        public Object getItem(int arg0) {
            return null;
        }

        @Override
        public long getItemId(int arg0) {
            return 0;
        }



        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            MainTiezi value = mList.get(position);
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_beautiful, null);
                holder.img1 = (ImageView) convertView.findViewById(R.id.img1);
                holder.img2 = (ImageView) convertView.findViewById(R.id.img2);
                holder.title1 = (TextView) convertView.findViewById(R.id.title1);
                holder.iv_zan1 = (ImageView) convertView.findViewById(R.id.iv_zan1);
                holder.title2 = (TextView) convertView.findViewById(R.id.title2);
                holder.iv_zan2 = (ImageView) convertView.findViewById(R.id.iv_zan2);
                holder.tv_zancount1 = (TextView) convertView.findViewById(R.id.tv_zancount1);
                holder.tv_zancount2 = (TextView) convertView.findViewById(R.id.tv_zancount2);
                holder.rl_tpcount1 = (RelativeLayout) convertView.findViewById(R.id.rl_tpcount1);
                holder.rl_tpcount2 = (RelativeLayout) convertView.findViewById(R.id.rl_tpcount2);
                holder.tv_tpcount1 = (TextView) convertView.findViewById(R.id.tv_tpcount1);
                holder.tv_tpcount2 = (TextView) convertView.findViewById(R.id.tv_tpcount2);
                holder.rl1 = (RelativeLayout) convertView.findViewById(R.id.rl1);
                holder.rl2 = (RelativeLayout) convertView.findViewById(R.id.rl2);
                android.view.ViewGroup.LayoutParams lParams1 = holder.rl1.getLayoutParams();
                android.view.ViewGroup.LayoutParams lParams2 = holder.rl2.getLayoutParams();
                lParams1.width =
                        (CommonParameter.sScreenWidth - CommonUtil.dp2px(getActivity(), 15)) / 2;
                lParams1.height =
                        (CommonParameter.sScreenWidth - CommonUtil.dp2px(getActivity(), 15)) / 2;
                lParams2.width =
                        (CommonParameter.sScreenWidth - CommonUtil.dp2px(getActivity(), 15)) / 2;
                lParams2.height =
                        (CommonParameter.sScreenWidth - CommonUtil.dp2px(getActivity(), 15)) / 2;
                android.view.ViewGroup.LayoutParams lp1 = holder.img1.getLayoutParams();
                android.view.ViewGroup.LayoutParams lp2 = holder.img2.getLayoutParams();
                lp1.width =
                        (CommonParameter.sScreenWidth - CommonUtil.dp2px(getActivity(), 19)) / 2;
                lp1.height =
                        (CommonParameter.sScreenWidth - CommonUtil.dp2px(getActivity(), 19)) / 2;
                lp2.width =
                        (CommonParameter.sScreenWidth - CommonUtil.dp2px(getActivity(), 19)) / 2;
                lp2.height =
                        (CommonParameter.sScreenWidth - CommonUtil.dp2px(getActivity(), 19)) / 2;
                holder.img2.setScaleType(ScaleType.FIT_XY);
                holder.img1.setScaleType(ScaleType.FIT_XY);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }



            if (num == position + 1 && mList.size() % 2 == 1) {

                holder.title1.setText(mList.get(position * 2).author);
                holder.tv_zancount1
                        .setText(Integer.parseInt(mList.get(position * 2).recommend_add) > 0 ? mList
                                .get(position * 2).recommend_add : "赞");

                if (mList.get(position * 2).pics.size() > 0) {
                    ImageLoader.getInstance().displayImage(mList.get(position * 2).pics.get(0).url,
                            holder.img1);
                } else {
                    ImageLoader.getInstance().displayImage("", holder.img1);
                }

                if (Integer.parseInt(mList.get(position * 2).picnum) > 0) {
                    holder.rl_tpcount1.setVisibility(View.VISIBLE);
                    holder.tv_tpcount1.setText(mList.get(position * 2).picnum + "张");
                } else {
                    holder.rl_tpcount1.setVisibility(View.GONE);
                }

                if (mList.get(position * 2).recommendmy.equals("1")) {
                    holder.iv_zan1.setImageResource(R.drawable.dianzan_c);
                } else {
                    holder.iv_zan1.setImageResource(R.drawable.dianzan_n);
                }


                holder.rl1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        // Intent intent =
                        // new Intent(mContext,
                        // com.xindaoapp.happypet.ui.PostDetailActivity.class);
                        // intent.putExtra(Constants.KEY_POST_TID, mList.get(position * 2).tid);
                        // intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                        // mContext.startActivity(intent);
                        // Intent intent =
                        // new Intent(mContext,
                        // com.xindaoapp.happypet.ui.PostDetailActivity.class);
                        // intent.putExtra(Constants.KEY_POST_TID, list.get(position * 2).tid);
                        // intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                        // mContext.startActivity(intent);
                        startActivity(new Intent(getActivity(), SplashPictureActivity2.class));
                    }
                });

            } else {
                if (mList.get(position * 2).pics.size() > 0) {

                    ImageLoader.getInstance().displayImage(mList.get(position * 2).pics.get(0).url,
                            holder.img1);
                } else {
                    ImageLoader.getInstance().displayImage("", holder.img1);
                }
                if (Integer.parseInt(mList.get(position * 2).picnum) > 0) {
                    holder.rl_tpcount1.setVisibility(View.VISIBLE);
                    holder.tv_tpcount1.setText(mList.get(position * 2).picnum + "张");
                } else {
                    holder.rl_tpcount1.setVisibility(View.GONE);
                }
                holder.title1.setText(mList.get(position * 2).author);
                holder.tv_zancount1
                        .setText(Integer.parseInt(mList.get(position * 2).recommend_add) > 0 ? mList
                                .get(position * 2).recommend_add : "赞");
                if (mList.get((position * 2) + 1).pics.size() > 0) {
                    ImageLoader.getInstance().displayImage(
                            mList.get((position * 2) + 1).pics.get(0).url, holder.img2);
                } else {
                    ImageLoader.getInstance().displayImage("", holder.img2);
                }
                if (Integer.parseInt(mList.get((position * 2) + 1).picnum) > 0) {
                    holder.rl_tpcount2.setVisibility(View.VISIBLE);
                    holder.tv_tpcount2.setText(mList.get((position * 2) + 1).picnum + "张");
                } else {
                    holder.rl_tpcount2.setVisibility(View.GONE);
                }
                holder.title2.setText(mList.get((position * 2) + 1).author);
                holder.tv_zancount2
                        .setText(Integer.parseInt(mList.get((position * 2) + 1).recommend_add) > 0 ? mList
                                .get((position * 2) + 1).recommend_add : "赞");

                if (mList.get(position * 2).recommendmy.equals("1")) {
                    holder.iv_zan1.setImageResource(R.drawable.dianzan_c);
                } else {
                    holder.iv_zan1.setImageResource(R.drawable.dianzan_n);
                }

                if (mList.get(position * 2 + 1).recommendmy.equals("1")) {
                    holder.iv_zan2.setImageResource(R.drawable.dianzan_c);
                } else {
                    holder.iv_zan2.setImageResource(R.drawable.dianzan_n);
                }

                holder.rl1.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View arg0) {
                        // Intent intent =
                        // new Intent(mContext,
                        // com.xindaoapp.happypet.ui.PostDetailActivity.class);
                        // intent.putExtra(Constants.KEY_POST_TID, mList.get(position * 2).tid);
                        // intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                        // mContext.startActivity(intent);
                        // Intent intent =
                        // new Intent(mContext,
                        // com.xindaoapp.happypet.ui.PostDetailActivity.class);
                        // intent.putExtra(Constants.KEY_POST_TID, list.get(position * 2).tid);
                        // intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                        // mContext.startActivity(intent);
                        startActivity(new Intent(getActivity(), SplashPictureActivity2.class));
                    }
                });
                holder.rl2.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View arg0) {
                        // Intent intent =
                        // new Intent(mContext,
                        // com.xindaoapp.happypet.ui.PostDetailActivity.class);
                        // intent.putExtra(Constants.KEY_POST_TID, mList.get(position * 2 + 1).tid);
                        // intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                        // mContext.startActivity(intent);
                        // Intent intent =
                        // new Intent(mContext,
                        // com.xindaoapp.happypet.ui.PostDetailActivity.class);
                        // intent.putExtra(Constants.KEY_POST_TID, list.get(position * 2 + 1).tid);
                        // intent.putExtra(Constants.KEY_FROM_PAGE, 1);
                        // mContext.startActivity(intent);
                        startActivity(new Intent(getActivity(), SplashPictureActivity2.class));
                    }
                });
            }

            return convertView;
        }
    }

    class ViewHolder {
        private RelativeLayout rl1;
        private RelativeLayout rl2;
        private RelativeLayout rl_tpcount1;
        private RelativeLayout rl_tpcount2;
        private ImageView img1;
        private ImageView img2;
        private TextView title1;
        private TextView title2;
        private ImageView iv_zan1;
        private ImageView iv_zan2;
        private TextView tv_zancount1;
        private TextView tv_zancount2;
        private TextView tv_tpcount1;
        private TextView tv_tpcount2;
    }


}
